import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-07-29
 * Time: 22:28
 */
public class test2 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ret = new ArrayList<>();
        if(matrix==null || matrix.length==0 || matrix[0].length==0){
            return ret;
        }
        int rows = matrix.length,cols = matrix[0].length;
        // 标记是否访问过
        boolean[][] vis = new boolean[rows][cols];
        // 标记总数
        int total = rows * cols;
        int row = 0, col = 0;
        // 移动的方向
        int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
        int directionIndex = 0;
        for(int i=0;i<total;i++){
            // 添加元素
            ret.add(matrix[row][col]);
            vis[row][col] = true;
            int nextRow = row+directions[directionIndex][0],nextCol = col + directions[directionIndex][1];
            if(nextRow<0 || nextRow>=rows || nextCol<0 || nextCol>=cols || vis[nextRow][nextCol]){
                // 进行旋转
                directionIndex = (directionIndex+1) %4;
            }
            row += directions[directionIndex][0];
            col += directions[directionIndex][1];
        }
        return ret;
    }
}
